﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;

using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Threading;
using System.Windows.Interop;


namespace EasyX264_ver1._0
{
    class EnCod
    {
        [StructLayout(LayoutKind.Sequential)]   //传递数据结构
        public struct COPYDATASTRUCT
        {
            public IntPtr dwData;
            public int cbData;//字符串长度
            [MarshalAs(UnmanagedType.LPStr)]
            public string lpData;//字符串
        }

        public string filename;//**********************************参数传递***************************
        public string[] args;//************************************参数传递***************************

        private Process encode_process;//进程
        private const int WM_COPYDATA = 0x004A; //传输数据
        private static IntPtr WIN_HAND;                //主窗口进程

        [DllImport("User32.dll", EntryPoint = "FindWindow")]    //找到进程句柄
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("User32.dll", EntryPoint = "SendMessage")]
        private static extern int SendMessage
            (
            IntPtr hWnd, // 目标窗体句柄
            int Msg, // WM_COPYDATA    
            int wParam, // 自定义数值 first message parameter    
            ref COPYDATASTRUCT lParam // 结构体 second message parameter    
        );

        /// <summary>
        /// SendMessage To Window
        /// </summary>
        private static void SendMessage(string strMsg)   //向主窗口发送消息
        {
            COPYDATASTRUCT cds;
            cds.dwData = IntPtr.Zero;
            cds.lpData = strMsg;//注意：长度为字节数
            cds.cbData = System.Text.Encoding.Default.GetBytes(strMsg).Length + 1; // 消息来源窗体
            SendMessage(WIN_HAND, WM_COPYDATA, 0, ref  cds);
        }

        //创建转码进程
        private bool StartProcess()
        {
            try
            {
                string s = "";
                foreach (string arg in args)
                {
                    s = s + arg + " ";
                }
                s = s.Trim();
                encode_process = new Process();
                ProcessStartInfo startInfo = new ProcessStartInfo(filename, s);
                encode_process.StartInfo = startInfo;
                encode_process.StartInfo.UseShellExecute = false;       //是否指定操作系统外壳进程启动程序
                encode_process.StartInfo.RedirectStandardError = true;  //重定向输出信息
                encode_process.ErrorDataReceived += new DataReceivedEventHandler(OutPut);//返回消息处理函数
                encode_process.StartInfo.CreateNoWindow = true;
                encode_process.Start();
                encode_process.BeginErrorReadLine();
                encode_process.WaitForExit();
                encode_process.Close();
                encode_process.Dispose();

                return true;
            }
            catch (Exception ex)
            {
                SendMessage("Error");//发送错误提示信息
                MessageBox.Show("启动应用程序时出错！原因：" + ex.Message);
            }
            return false;
        }

        private void OutPut(object sendProcess, DataReceivedEventArgs output) //进程调用程序
        {
            if (String.IsNullOrEmpty(output.Data))
            {
                return;
            }
            SendMessage(output.Data);
        }

        //初始化启动转码
        public void init()
        {
            WIN_HAND = FindWindow(null, "EasyX264"); //找到窗口

            if (WIN_HAND == IntPtr.Zero)
            {
                MessageBox.Show("主窗体未找到!!");
            }

            else
            {
                //发送编码结束信息
                if (StartProcess() == true)
                {
                    if (filename == @"EnCoder\\x264 ")
                    {
                        SendMessage("Finish");
                    }
                }
               
            }
        }

        public void KILL()//关闭或取消应用程序时调用此方法
        {
            //注意资源释放!

            //判断如果进程没有结束则将其结束
            if (!encode_process.HasExited)
            {
                encode_process.Kill();
            }
        }
    }
}
